/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.hpvas.persistence.dao;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import edu.hpvas.persistence.entity.Person;
import edu.hpvas.persistence.entity.Appointment;
import edu.hpvas.persistence.entity.Pet;
import edu.hpvas.persistence.entity.Veterinarian;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author raider
 */
public class VeterinarianDAO implements Serializable {

    public VeterinarianDAO() {
        this.emf = Persistence.createEntityManagerFactory("HPVAS");
    }
    private EntityManagerFactory emf;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Veterinarian veterinarian) throws Exception {
        if (veterinarian.getAppointmentCollection() == null) {
            veterinarian.setAppointmentCollection(new ArrayList<Appointment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person idPerson = veterinarian.getIdPerson();
            if (idPerson != null) {
                idPerson = em.getReference(idPerson.getClass(), idPerson.getId());
                veterinarian.setIdPerson(idPerson);
            }
            Collection<Appointment> attachedAppointmentCollection = new ArrayList<Appointment>();
            for (Appointment appointmentCollectionAppointmentToAttach : veterinarian.getAppointmentCollection()) {
                appointmentCollectionAppointmentToAttach = em.getReference(appointmentCollectionAppointmentToAttach.getClass(), appointmentCollectionAppointmentToAttach.getId());
                attachedAppointmentCollection.add(appointmentCollectionAppointmentToAttach);
            }
            veterinarian.setAppointmentCollection(attachedAppointmentCollection);
            em.persist(veterinarian);
            if (idPerson != null) {
                idPerson.getVeterinarianCollection().add(veterinarian);
                idPerson = em.merge(idPerson);
            }
            for (Appointment appointmentCollectionAppointment : veterinarian.getAppointmentCollection()) {
                Veterinarian oldIdVeterinarianOfAppointmentCollectionAppointment = appointmentCollectionAppointment.getIdVeterinarian();
                appointmentCollectionAppointment.setIdVeterinarian(veterinarian);
                appointmentCollectionAppointment = em.merge(appointmentCollectionAppointment);
                if (oldIdVeterinarianOfAppointmentCollectionAppointment != null) {
                    oldIdVeterinarianOfAppointmentCollectionAppointment.getAppointmentCollection().remove(appointmentCollectionAppointment);
                    oldIdVeterinarianOfAppointmentCollectionAppointment = em.merge(oldIdVeterinarianOfAppointmentCollectionAppointment);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findVeterinarian(veterinarian.getId()) != null) {
                System.out.println("Veterinarian " + veterinarian + " already exists.");
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Veterinarian veterinarian,Veterinarian newVeterinarian) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            veterinarian= findVeterinarian(veterinarian.getId());
            veterinarian.setFocusOfPractice(newVeterinarian.getFocusOfPractice());
            veterinarian.setGraduateAt(newVeterinarian.getGraduateAt());
            veterinarian.setSalary(newVeterinarian.getSalary());
            veterinarian.setSpecialities(newVeterinarian.getSpecialities());
            em.merge(veterinarian);
            /*
             
            Veterinarian persistentVeterinarian = em.find(Veterinarian.class, veterinarian.getId());
            Person idPersonOld = persistentVeterinarian.getIdPerson();
            Person idPersonNew = veterinarian.getIdPerson();
            Collection<Appointment> appointmentCollectionOld = persistentVeterinarian.getAppointmentCollection();
            Collection<Appointment> appointmentCollectionNew = veterinarian.getAppointmentCollection();
            if (idPersonNew != null) {
                idPersonNew = em.getReference(idPersonNew.getClass(), idPersonNew.getId());
                veterinarian.setIdPerson(idPersonNew);
            }
            Collection<Appointment> attachedAppointmentCollectionNew = new ArrayList<Appointment>();
            for (Appointment appointmentCollectionNewAppointmentToAttach : appointmentCollectionNew) {
                appointmentCollectionNewAppointmentToAttach = em.getReference(appointmentCollectionNewAppointmentToAttach.getClass(), appointmentCollectionNewAppointmentToAttach.getId());
                attachedAppointmentCollectionNew.add(appointmentCollectionNewAppointmentToAttach);
            }
            appointmentCollectionNew = attachedAppointmentCollectionNew;
            veterinarian.setAppointmentCollection(appointmentCollectionNew);
            veterinarian = em.merge(veterinarian);
            if (idPersonOld != null && !idPersonOld.equals(idPersonNew)) {
                idPersonOld.getVeterinarianCollection().remove(veterinarian);
                idPersonOld = em.merge(idPersonOld);
            }
            if (idPersonNew != null && !idPersonNew.equals(idPersonOld)) {
                idPersonNew.getVeterinarianCollection().add(veterinarian);
                idPersonNew = em.merge(idPersonNew);
            }
            for (Appointment appointmentCollectionOldAppointment : appointmentCollectionOld) {
                if (!appointmentCollectionNew.contains(appointmentCollectionOldAppointment)) {
                    appointmentCollectionOldAppointment.setIdVeterinarian(null);
                    appointmentCollectionOldAppointment = em.merge(appointmentCollectionOldAppointment);
                }
            }
            for (Appointment appointmentCollectionNewAppointment : appointmentCollectionNew) {
                if (!appointmentCollectionOld.contains(appointmentCollectionNewAppointment)) {
                    Veterinarian oldIdVeterinarianOfAppointmentCollectionNewAppointment = appointmentCollectionNewAppointment.getIdVeterinarian();
                    appointmentCollectionNewAppointment.setIdVeterinarian(veterinarian);
                    appointmentCollectionNewAppointment = em.merge(appointmentCollectionNewAppointment);
                    if (oldIdVeterinarianOfAppointmentCollectionNewAppointment != null && !oldIdVeterinarianOfAppointmentCollectionNewAppointment.equals(veterinarian)) {
                        oldIdVeterinarianOfAppointmentCollectionNewAppointment.getAppointmentCollection().remove(appointmentCollectionNewAppointment);
                        oldIdVeterinarianOfAppointmentCollectionNewAppointment = em.merge(oldIdVeterinarianOfAppointmentCollectionNewAppointment);
                    }
                }
            }*/
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = veterinarian.getId();
                if (findVeterinarian(id) == null) {
                    System.out.println("The veterinarian with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id){
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinarian veterinarian = null;
            try {
                veterinarian = em.getReference(Veterinarian.class, id);
                veterinarian.getId();
            } catch (EntityNotFoundException enfe) {
                System.out.println("The veterinarian with id " + id + " no longer exists.");
            }
            Person idPerson = veterinarian.getIdPerson();
            if (idPerson != null) {
                idPerson.getVeterinarianCollection().remove(veterinarian);
                idPerson = em.merge(idPerson);
            }
            Collection<Appointment> appointmentCollection = veterinarian.getAppointmentCollection();
            for (Appointment appointmentCollectionAppointment : appointmentCollection) {
                appointmentCollectionAppointment.setIdVeterinarian(null);
                appointmentCollectionAppointment = em.merge(appointmentCollectionAppointment);
            }
            em.remove(veterinarian);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Veterinarian> findVeterinarianEntities() {
        return findVeterinarianEntities(true, -1, -1);
    }

    public List<Veterinarian> findVeterinarianEntities(int maxResults, int firstResult) {
        return findVeterinarianEntities(false, maxResults, firstResult);
    }

    private List<Veterinarian> findVeterinarianEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Veterinarian.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Veterinarian findVeterinarian(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Veterinarian.class, id);
        } finally {
            em.close();
        }
    }
    
    public Veterinarian findVeterinarianEntitiesByName(String name){
        EntityManager em=getEntityManager();
        Query query= em.createQuery("select v from Veterinarian v where v.idPerson.name=:name").setParameter("name", name);
        if(!query.getResultList().isEmpty()) {
            return (Veterinarian) query.getSingleResult();
        }
        else {
            return null;
        }
    }

    public int getVeterinarianCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Veterinarian> rt = cq.from(Veterinarian.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    public Veterinarian findVeterinarianByIdPerson(Person person){
        EntityManager em=getEntityManager();
        Query query= em.createQuery("select v from Veterinarian v where v.idPerson=:idPerson").setParameter("idPerson",
                person);
        if(!query.getResultList().isEmpty()) {
            return (Veterinarian) query.getSingleResult();
        }
        else {
            return null;
        }
    }
    
}
